package com.suyl.candy.weather.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * http远程调用工具类
 */
public class HttpClientUtils {

    /**
     * GET请求远程调用
     *
     * @param url
     * @return
     */
    public static Object get(String url) {
        try {
            //创建默认连接
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建HttpGet对象,处理get请求,转发到A站点
            HttpGet httpGet = new HttpGet(url);
            //执行
            CloseableHttpResponse response = null;

            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
            response = httpClient.execute(httpGet);

            int code = response.getStatusLine().getStatusCode();
            //获取状态
            if (code == 200) {
                //获取A站点返回的结果
                String result = EntityUtils.toString(response.getEntity());
//                resp.getWriter().print(result);
                //把结果返回给B站点
                return result;
            }
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
